package com.uyaer.card.plus
{
	import flash.events.AccelerometerEvent;
	import flash.sensors.Accelerometer;
	import com.uyaer.card.common.Dir;

	/**
	 *感应器 
	 * @author hc
	 * 
	 */	
	public class Sensor
	{
		/**
		 *类型 方向 
		 */		
		public static const DIR:String = "dir";
		/**
		 *类型 晃动 
		 */		
		public static const SHAKE:String = "shake";
		
		private static var m_instance:Sensor;
		private var acc:Accelerometer;
		private var isRuning:Boolean = false;
		private var type:String;
		private var DIR_MAX:Number = 0.35;
		private var DIR_MIN:Number = 0.2;
		public function Sensor()
		{
			
		}
		
		public static function get instance():Sensor{
			return m_instance ||= new Sensor(); 
		}
		
		public function start(type:String = DIR):void{
			this.type = type;
			if(isRuning){
				this.stop();
			}
			if(!acc){
				acc = new Accelerometer();
			}
			acc.addEventListener(AccelerometerEvent.UPDATE,accUpdate);
			isRuning = true;
		}
		
		public function stop():void{
			acc.removeEventListener(AccelerometerEvent.UPDATE,accUpdate);
			isRuning = false;
		}
		
		private function accUpdate(e:AccelerometerEvent):void{
			switch(type){
				case DIR:
					updateDir(e);
					break;
				case SHAKE:
					break;
			}
			
		}
		
		private function updateDir(e:AccelerometerEvent):void{
			var zDir:int = -1;
			if(e.accelerationZ < 0 ) zDir = 1;
			Dir.dirX = e.accelerationX * zDir;
			Dir.dirY = e.accelerationY;
			//限定值范围
			if(Dir.dirX<0){
				if(Dir.dirX<-DIR_MAX) Dir.dirX = -DIR_MAX;
				if(Dir.dirX>-DIR_MIN) Dir.dirX = -DIR_MIN;
			}
			if(Dir.dirY<0){
				if(Dir.dirY<-DIR_MAX) Dir.dirY = -DIR_MAX;
				if(Dir.dirY>-DIR_MIN) Dir.dirY = -DIR_MIN;
			}
			if(Dir.dirX>0){
				if(Dir.dirX>DIR_MAX) Dir.dirX = DIR_MAX;
				if(Dir.dirX<DIR_MIN) Dir.dirX = DIR_MIN;
			}
			if(Dir.dirY>0){
				if(Dir.dirY>DIR_MAX) Dir.dirY = DIR_MAX;
				if(Dir.dirY<DIR_MIN) Dir.dirY = DIR_MIN;
			}
		}
		
		/**
		 *是否支持加速器 
		 * @return 
		 * 
		 */		
		public static function get support():Boolean{
			return Accelerometer.isSupported;
		}
	}
}